﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using Microsoft.Ajax.Utilities;

namespace ContosoUniversity.DAL
{
    public class SchoolInterceptorLogging : DbCommandInterceptor
    {
        private ILogger _logger = new Logger();
        private readonly Stopwatch _stopwatch = new Stopwatch();

        public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            _stopwatch.Stop();
            if (interceptionContext.Exception != null)
            {
                _logger.Error("Error executing command: "+command.CommandText,interceptionContext.Exception);
            }
            else
            {
                _logger.TraceApi("SQL Database","SchoolInterceptor.NonQueryExecuted",_stopwatch.Elapsed,"Command: {0}: ",command.CommandText);
            }
            base.NonQueryExecuted(command,interceptionContext);
        }

        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            base.NonQueryExecuting(command,interceptionContext);
            _stopwatch.Restart();
        }

        public override void ReaderExecuted(DbCommand command,
            DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            _stopwatch.Stop();
            if (interceptionContext.Exception != null)
            {
                _logger.Error(interceptionContext.Exception,"Error executing command: {0}",command.CommandText);
            }
            else
            {
                _logger.TraceApi("SQL Database","SchoolInterceptor.ReaderExecuted",_stopwatch.Elapsed,"Command: {0}: ",command.CommandText);
            }
            base.ReaderExecuted(command,interceptionContext);
        }

        public override void ReaderExecuting(DbCommand command,
            DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            base.ReaderExecuting(command,interceptionContext);
            _stopwatch.Restart();
        }

        public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            //
        }

        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            base.ScalarExecuting(command,interceptionContext);
            _stopwatch.Restart();
        }
    }
}
